/**
 * @author Evgeny Sorokin
 */
Ext.define('USocial.controller.ApproachCheck',{
	extend : 'Ext.app.Controller',
	
	init : function(){
		
		var APPROACHING_DISTANCE = 0.3; //km
		
		var friendsStore = Ext.getStore('FriendsStore');
			appUserStore = Ext.getStore('AppUserStore');
			
		
		function isShortDistance(user1, user2){
			if(USocial.util.Geolocation.computeDistance(user1, user2) < APPROACHING_DISTANCE){
				return true;
			}
			return false;
		}
		
		/*
		 * Approaching action
		 * */
		function checkDistance(appUser, friend){
			console.log('user:'+appUser.getPosition()+' friend:'+friend.getPosition()+' checked'+friend.get('checked'));
			if(appUser.getPosition() && friend.getPosition() && !friend.get('checked')){
				if(isShortDistance(appUser, friend)){
					USocial.app.fireEvent('approach', appUser, friend);
				}
			}
		}
		
		//friend is approaching to user
		friendsStore.on('updaterecord', function(store, friend, newIndex, oldIndex, modifiedFieldNames){
			if(USocial.util.Geolocation.userLocationUpdated(friend)){
				var appUser = USocial.Util.getAppUser();
				if(appUser){
					checkDistance(appUser, friend);
				}
			}
		});
		
		//user is approaching to friend
		appUserStore.on('updaterecord', function(store, appUser, newIndex, oldIndex, modifiedFieldNames){
			if(USocial.util.Geolocation.userLocationUpdated(appUser)){
				var distance;
				friendsStore.getData().items.forEach(function(friend){
					checkDistance(appUser, friend);
				});
			}
		});
	}
});